package com.thrd.basicframework.ui.recyclerview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SnapHelper;

import com.thrd.basicframework.R;

/**
 * @author: ${唐杰}
 * @date: 2021/3/26
 */
public class RecyclerViewIndicator extends FrameLayout {
    private RecyclerView mRecyclerView;
    private com.thrd.basicframework.ui.recyclerview.RecyclerIndicatorView.RecyclerViewIndicator  mRecyclerViewIndicator;
    private boolean indicatorCarousel;
    private int indicatorCarouselTime;
    private SnapHelper mSnapHelper;

    public RecyclerViewIndicator(@NonNull Context context) {
        this(context, null);
    }

    public RecyclerViewIndicator(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RecyclerViewIndicator(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        View root = inflate(context, R.layout.app_viewpager_indicator, this);
        mRecyclerView = root.findViewById(R.id.rv_recyclerview);
        mRecyclerViewIndicator = root.findViewById(R.id.recyclerViewIndicator);
        initView(context,attrs);
        initData();

    }
    @SuppressLint("ClickableViewAccessibility")
    private void initData() {

        mRecyclerView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_DOWN||event.getAction()==MotionEvent.ACTION_MOVE){
                 //   Log.e("ViewPageIndicator","按下");
                    stopCarousel();
                }else if(event.getAction()==MotionEvent.ACTION_UP){
                    startCarousel();
                //    Log.e("ViewPageIndicator","弹起");
                }
              //  Log.e("ViewPageIndicator","MotionEvent="+event.getAction());
                return false;
            }
        });

        mRecyclerView.addOnScrollListener(new RecyclerViewPageChangeListenerHelper(mSnapHelper,
                new RecyclerViewPageChangeListenerHelper.OnPageChangeListener() {
                    @Override
                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                        // Log.e("Zorro", "选中" + newState);
                    }

                    @Override
                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                //        Log.e("Zorro", "dx" + dx+"dy"+dy);
                    }

                    @Override
                    public void onPageSelected(int position) {
                        carousePosition=position;

                    }
                }));


    }

    @SuppressLint("WrongConstant")
    private void  initView(Context context, AttributeSet attrs){
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AnyViewIndicator);
        mRecyclerViewIndicator.setIndicatorWidth(typedArray.getDimensionPixelSize(R.styleable.AnyViewIndicator_avi_width, -1));
        mRecyclerViewIndicator.setIndicatorHeight(typedArray.getDimensionPixelSize(R.styleable.AnyViewIndicator_avi_height, -1));
        mRecyclerViewIndicator.setIndicatorMargin(typedArray.getDimensionPixelSize(R.styleable.AnyViewIndicator_avi_margin, -1));
        mRecyclerViewIndicator.setAnimatorResId(typedArray.getResourceId(R.styleable.AnyViewIndicator_avi_animator,
                R.animator.scale_with_alpha));
        mRecyclerViewIndicator.setAnimatorReverseResId(typedArray.getResourceId(R.styleable.AnyViewIndicator_avi_animator_reverse, 0));
        mRecyclerViewIndicator.setIndicatorBackgroundResId(typedArray.getResourceId(R.styleable.AnyViewIndicator_avi_drawable,
                R.drawable.white_radius));
        mRecyclerViewIndicator.setIndicatorUnselectedBackgroundResId(typedArray.getResourceId(R.styleable.AnyViewIndicator_avi_drawable_unselected,
                R.drawable.white_radius));
        mRecyclerViewIndicator.setAnimationEnable(typedArray.getBoolean(R.styleable.AnyViewIndicator_avi_animation_enable, true));

        int orientation=typedArray.getInt(R.styleable.AnyViewIndicator_avi_orientation, -1);
        mRecyclerViewIndicator.setOrientation(orientation == RecyclerView.VERTICAL ? RecyclerView.VERTICAL : RecyclerView.HORIZONTAL);

        int gravity = typedArray.getInt(R.styleable.AnyViewIndicator_avi_gravity, -1);
        mRecyclerViewIndicator.setGravity(gravity >= 0 ? gravity : Gravity.CENTER);

        indicatorCarousel = typedArray.getBoolean(R.styleable.AnyViewIndicator_avi_carousel,false);
        indicatorCarouselTime = typedArray.getInt(R.styleable.AnyViewIndicator_avi_carousel_time,3000);
        typedArray.recycle();

        mSnapHelper = new PagerSnapHelper();

    }

    public void setLayoutManager(RecyclerView.LayoutManager manager) {
        mRecyclerView.setLayoutManager(manager);
        mSnapHelper.attachToRecyclerView(mRecyclerView);

    }


    private int  adapterSize;
    private Handler mHandler=new Handler(Looper.getMainLooper());
    //当前显示页面数
    private int carousePosition=0;


    public void setAdapter(RecyclerView.Adapter adapter){
        mRecyclerView.setAdapter(adapter);
        mRecyclerViewIndicator.setRecyclerView(mRecyclerView);
        //如果需要更改适配器大小，则应调用此函数
        forceUpdateItemCount();
        adapterSize=adapter.getItemCount();
        startCarousel();
    }

    public RecyclerView.Adapter getAdapter(){
        return mRecyclerView==null?null:mRecyclerView.getAdapter();
    }

    //如果需要更改适配器大小，则应调用此函数
    public void forceUpdateItemCount(){
        //如果需要更改适配器大小，则应调用此函数
        mRecyclerViewIndicator.forceUpdateItemCount();
        if(mRecyclerView!=null&&mRecyclerView.getAdapter()!=null){
            adapterSize=mRecyclerView.getAdapter().getItemCount();

        }
        startCarousel();

    }

    /**
     * 开启轮播
     */
    private void startCarousel(){
        if(adapterSize>1&&indicatorCarousel){
            stopCarousel();
            if(mHandler==null){
                mHandler=new Handler(Looper.getMainLooper());
            }
            mHandler.removeCallbacks(runnable);
            mHandler.postDelayed(runnable,indicatorCarouselTime);
            Log.e("ViewPageIndicator","定时器开启");
        }
    }
    /**
     * 关闭轮播
     */
    private void stopCarousel(){
        if(mHandler!=null){
            Log.e("ViewPageIndicator","定时器关闭");
            mHandler.removeCallbacks(runnable);
        }
    }


    private Runnable runnable=new Runnable() {
        @Override
        public void run() {
            if(mRecyclerView!=null){
                mRecyclerView.smoothScrollToPosition((carousePosition+1)>=adapterSize?carousePosition=0:++carousePosition);
                Log.e("ViewPageIndicator","carousePosition="+carousePosition);
                mHandler.removeCallbacks(runnable);
                mHandler.postDelayed(runnable,indicatorCarouselTime);
            }
        }
    };



    /**
     * 跳转页面
     * @param item
     */
    public void setCurrentItem(int item){
        if(mRecyclerView!=null){
            stopCarousel();
            mRecyclerView.smoothScrollToPosition(item);
            carousePosition=item;
            startCarousel();
        }
    }


    public int  getCurrentItem(){
        return carousePosition;
    }

    /**
     * 对用户不可见
     */
    public void onFragmentPause() {
        stopCarousel();

    }

    /**
     * 对用户可见
     */
    public void onFragmentResume() {
        startCarousel();
    }

    /**
     * 结束所有状态
     */
    public void onDestroy(){
        stopCarousel();
        mHandler=null;
        if(mRecyclerView!=null){
            mRecyclerView.setOnTouchListener(null);
            mRecyclerView=null;
        }

    }


}
